<template>
  <el-form
    ref="fromdata1"
    :model="formData"
    label-width="100px"
    label-position="right"
  >
    <base-layout
      :dialog-title="dialogTitle"
      :dialog-visible="dialogVisible"
      visibleContent2
      @dialog-close="dialogClose"
    >
      <template #searchPanel>
        <el-row>
          <el-col :span="12">资金利息信息</el-col>
          <el-divider content-position="center"></el-divider>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="申请单号:" prop="code">
              <el-input
                :disabled="isView"
                readonly
                v-model="formData.code"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标题:" prop="title">
              <el-input
                :disabled="isView"
                clearable
                v-model="formData.title"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="所属门店:" prop="storeIds">
              <el-select
                :disabled="isView"
                multiple
                collapse-tags
                clearable
                v-model="formData.storeIds"
                placeholder="请选择门店"
              >
                <el-option
                  v-for="item in stores"
                  :key="item.id"
                  :value="item.id"
                  :label="item.storeName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请人:" prop="sqrName">
              <el-input
                :disabled="isView"
                readonly
                v-model="formData.sqrName"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请日期:" prop="sqTime">
              <el-date-picker
                :disabled="isView"
                v-model="formData.sqTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="date"
                placeholder="到期时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template #contentPanel>
        <el-row>
          <el-col :span="12">价格政策车型信息</el-col>
          <el-col :span="12" class="text-right">
            <el-button type="primary" @click="addCarModel" v-if="!isView"
              ><i class="el-icon-plus"></i> 添加车型</el-button
            >
          </el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <data-table
          :value="formData.cxList"
          :has-action="false"
          :table-column-attributes="tableColumnAttributes"
          :width="160"
          :isShowPage="false"
        >
        </data-table>
        <div class="text-right mt-10" v-if="!isView">
          <el-button
            v-permission="!$route.params.id ? authConfig.add : authConfig.edit"
            type="success"
            @click="saveUpdate"
            >保存</el-button
          >
        </div>
      </template>
      <template #dialog>
        <SelectCarModel @getList="addCarModelBack" />
      </template>
    </base-layout>
  </el-form>
</template>

<script>
import {
  addData,
  updateData,
  getCode,
  details,
} from '@/api/pre-sale/newCarStock/newCarSaleManagement'
import baseMixin from '@/mixins/base'
import { parseTimeToYMDHMS } from '@/utils'
import { getDict } from '@/utils/index'
import { SelectCarModel } from '@/components/index'
import { mapGetters } from 'vuex'

export default {
  components: { SelectCarModel },
  computed: {
    ...mapGetters(['stores', 'userInfo']),
    tableDataMap() {
      const map = {}
      this.formData.cxList.forEach((item, index) => {
        map[item.id] = index
      })
      return map
    },
  },
  mixins: [
    baseMixin({
      addData: addData,
      updateData: updateData,
      format(res) {
        return res.map((data) => {
          return data
        })
      },
    }),
  ],
  data() {
    return {
      authConfig: {
        add: 'jgzczd:save',
        edit: 'jgzczd:update',
      },
      isView: false,
      formData: {
        code: '',
        title: '',
        sqrId: '',
        sqrName: '',
        storeIds: '',
        sqTime: parseTimeToYMDHMS(new Date()),
        cxList: [],
      },
      tableColumnAttributes: [
        { name: '开始日期', value: 'startTime', type: 'date' },
        { name: '结束日期', value: 'endTime', type: 'date' },
        { name: '让价金额', value: 'rjPrice', type: 'inputNumber' },
        { name: '让价类型', value: 'rjType', type: 'select',
          options: getDict(['让价类型'])['让价类型'].map((item) => {
            return { id: item.value + '', value: item.text }
          }) },
        { name: '品牌', value: 'carBrandName', type: 'text' },
        { name: '车系', value: 'carSeriesName', type: 'text' },
        { name: '车型', value: 'carModelName', type: 'text' },
        { name: '指导价', value: 'bzPrice', type: 'text' },
        { name: '实际进价', value: 'sjPrice', type: 'inputNumber' }
      ],
    }
  },
  methods: {
    // 添加车型M模态框
    addCarModel() {
      this.dialogVisible = true
    },
    // 添加车型
    addCarModelBack(selection) {
      const tableList = []
      selection.forEach((item) => {
        if (!this.tableDataMap[item.id]) {
          tableList.push({
            // id: item.id,
            // 标准进价
            bzPrice: item.guidePrice,
            carBrandId: item.brandId, // 品牌id
            carBrandName: item.brandName,
            carSeriesId: item.seriesId, //车系
            carSeriesName: item.seriesName,
            carModelId: item.id, // 车型
            carModelName: item.modelName,
            startTime: '', // 开始时间
            endTime: '', // 结束时间
            rjPrice: '', // 让价金额
            rjType: '', //让价类型
            sjPrice: '', //实际进价
          })
        }
      })
      this.formData.cxList.push(...tableList)
      this.dialogVisible = false
    },
    // 保存数据
    saveUpdate() {
      this.$refs['fromdata1'].validate((valid) => {
        if (valid) {
          let options = JSON.parse(JSON.stringify(this.formData))
          options.storeIds = options.storeIds.join(',')
          options.sqTime = options.sqTime
            ? parseTimeToYMDHMS(options.sqTime)
            : ''
          this.saveSuppierData(options)
        }
      })
    },

    async saveSuppierData(params) {
      const { success } = this.formData.id
        ? await updateData(params)
        : await addData(params)
      if (success) {
        this.$message({
          message: '操作成功',
          type: 'success',
        })
        this.$router.push({
          path: '/newCarStock/newCarSaleManagement/pricePolicyMaking',
        })
      } else {
        this.$message.error('操作失败')
      }
    },
    // 查询详情
    async detail(id) {
      let { data } = await details(id)
      this.formData = data
      this.formData.confirmPwd = data.loginPwd
      this.formData.storeIds = [data.storeId]
    },
    // 查询详情
    async getCode(id) {
      let { data } = await getCode()
      this.formData.code = data
    },
  },
  created() {},
  mounted() {
    const id = this.$route.query && this.$route.query.id
    this.isView = this.$route.query && this.$route.query.isView
    this.formData.sqrId = this.userInfo.id
    this.formData.sqrName = this.userInfo.userName
    // this.formData.sqrName = store.state.user.userInfo.userName
    if (id) {
      this.formData.id = id
      this.detail(id)
    } else {
      this.getCode()
    }
  },
}
</script>

<style lang="scss" scoped>
</style>
